import { useRequest, useWatcher } from "alova/client";
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputProps,
  Row,
  Typography,
  DatePicker,
  Spin,
  Alert,
  App,
  Select,
  Table, // 导入 Table 组件
  Modal, // 导入 Modal 组件用于编辑和新增弹窗
} from "antd";
import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import "../styles/maintainAdd.css";
import { Space } from "antd";
import TencentCOSUpload, {
  TencentCOSUploadRef,
} from "../components/TencentCOSUpload";
import {
  ContractViewVO,
  MaintainRecordInsertVO,
  MediaVO,
} from "../api/globals";

const { Item } = Form;
const { Option } = Select;

const MaintainAdd: React.FC = () => {
  const [form] = Form.useForm<MaintainRecordInsertVO & ContractViewVO>();
  const navigate = useNavigate();
  const [contractCode, setContractCode] = useState<string>("");
  const fileRef = useRef<TencentCOSUploadRef | null>(null);
  const { message: appMessage } = App.useApp();

  const { data, loading, error } = useWatcher(
    () =>
      Apis.cm.Wci({
        pathParams: {
          contractCode: contractCode,
        },
      }),
    [contractCode],
    {
      immediate: contractCode.length > 0,
    }
  );

  const handleContractCodeBlur: InputProps["onBlur"] = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const value = e.target.value.trim();
    if (value) {
      setContractCode(value);
      form.setFieldsValue({ contractCode: value });
    }
  };

//   React.useEffect(() => {
//     if (data) {
//       form.setFieldsValue({
//         houseCode: data.houseCode,
//         name: data.name,
//         contactName: data.contactName,
//         contactMobile: data.contactMobile,
//         address: data.address,
//         productName: data.productName,
//         productStartTime: data.productStartTime
//           ? dayjs(data.productStartTime)
//           : null,
//         productEndTime: data.productEndTime
//           ? dayjs(data.productEndTime)
//           : null,
//         lastMaintainTime: data.lastMaintainTime
//           ? dayjs(data.lastMaintainTime)
//           : null,
//       });
//     }
//   }, [data, form]);

//   const { loading: submitLoading, send: submitMT } = useRequest(() =>
//     Apis.mt.Add({
//       data: form.getFieldsValue(),
//     })
//   );


  // 施工方表格数据
  const [constructionCompanies, setConstructionCompanies] = useState<{
    key: React.Key;
    companyName: string;
    principalName: string;
    phone: string;
  }[]>([]);

  // 监理方表格数据
  const [supervisors, setSupervisors] = useState<{
    key: React.Key;
    supervisorCompany: string;
    supervisorName: string;
    supervisorPhone: string;
  }[]>([]);

  // 监理方弹窗相关状态
  const [isSupervisorModalVisible, setIsSupervisorModalVisible] = useState(false);
  const [supervisorEditingKey, setSupervisorEditingKey] = useState("");
  const [supervisorModalForm] = Form.useForm<{
    supervisorCompany: string;
    supervisorName: string;
    supervisorPhone: string;
  }>();

  // 显示监理方弹窗
  const showSupervisorModal = (record?: {
    key: React.Key;
    supervisorCompany: string;
    supervisorName: string;
    supervisorPhone: string;
  }) => {
    if (record) {
      supervisorModalForm.setFieldsValue(record);
      setSupervisorEditingKey(record.key);
    } else {
      supervisorModalForm.resetFields();
      setSupervisorEditingKey("");
    }
    setIsSupervisorModalVisible(true);
  };

  // 处理监理方弹窗确认
  const handleSupervisorModalOk = () => {
    supervisorModalForm
      .validateFields()
      .then((values) => {
        if (supervisorEditingKey) {
          setSupervisors((prev) =>
            prev.map((item) =>
              item.key === supervisorEditingKey
                ? { ...item, ...values, key: supervisorEditingKey }
                : item
            )
          );
        } else {
          setSupervisors((prev) => [
            ...prev,
            { ...values, key: Date.now().toString() },
          ]);
        }
        setIsSupervisorModalVisible(false);
      })
      .catch((error) => {
        console.log("Supervisor Modal form validation error", error);
      });
  };

  // 处理监理方弹窗取消
  const handleSupervisorModalCancel = () => {
    setIsSupervisorModalVisible(false);
  };

  // 删除监理方记录
  const handleSupervisorDelete = (key: React.Key) => {
    setSupervisors((prev) => prev.filter((item) => item.key !== key));
  };

  // 监理方表格列配置
  const supervisorColumns = [
    {
      title: "监理方",
      dataIndex: "supervisorCompany",
      key: "supervisorCompany",
    },
    {
      title: "监理负责人姓名",
      dataIndex: "supervisorName",
      key: "supervisorName",
    },
    {
      title: "监理负责人电话",
      dataIndex: "supervisorPhone",
      key: "supervisorPhone",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => showSupervisorModal(record)}>编辑</Button>
          <Button onClick={() => handleSupervisorDelete(record.key)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 弹窗相关状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingKey, setEditingKey] = useState("");
  const [modalForm] = Form.useForm<{
    companyName: string;
    principalName: string;
    phone: string;
  }>();

  // 显示弹窗
  const showModal = (record?: {
    key: React.Key;
    companyName: string;
    principalName: string;
    phone: string;
  }) => {
    if (record) {
      modalForm.setFieldsValue(record);
      setEditingKey(record.key);
    } else {
      modalForm.resetFields();
     setEditingKey("");
    }
    setIsModalVisible(true);
  };

  // 处理弹窗���认
  const handleModalOk = () => {
    modalForm
      .validateFields()
      .then((values) => {
        if (editingKey) {
          setConstructionCompanies((prev) =>
            prev.map((item) =>
              item.key === editingKey
                ? { ...item, ...values, key: editingKey }
                : item
            )
          );
        } else {
          setConstructionCompanies((prev) => [
            ...prev,
            { ...values, key: Date.now().toString() },
          ]);
        }
        setIsModalVisible(false);
      })
      .catch((error) => {
        console.log("Modal form validation error", error);
      });
  };

  // 处理弹窗取消
  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  // 删除记录
  const handleDelete = (key: React.Key) => {
    setConstructionCompanies((prev) =>
      prev.filter((item) => item.key !== key)
    );
  };

  // 表格列配置
  const columns = [
    {
      title: "公司名称",
      dataIndex: "companyName",
      key: "companyName",
    },
    {
      title: "负责人姓名",
      dataIndex: "principalName",
      key: "principalName",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => showModal(record)}>编辑</Button>
          <Button onClick={() => handleDelete(record.key)}>删除</Button>
        </Space>
      ),
    },
  ];

  const renderContractInfo = () => {

    return (
      <>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="工程名称" name="houseCode">
            <Input  />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="工程编号" name="name">
            <Input  />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="开始时间" name="productStartTime">
            <DatePicker style={{ width: "100%" }} />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="结束时间" name="productEndTime">
            <DatePicker style={{ width: "100%" }} />
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={128} xl={126}>
          <Item
            label="立项报告"
            name="contactName"
            wrapperCol={{
              style: {
                textAlign: "right",
              },
            }}
          >
            <Button
              type="primary"
            >
              上传附件
            </Button>
          </Item>
        </Col>
        <Col xs={24} sm={12} md={128} lg={128} xl={126}>
          <Item
            label="招标文件"
            name="contactMobile"
            wrapperCol={{
              style: {
                textAlign: "right",
              },
            }}
          >
            <Button
              type="primary"
            >
              上传附件
            </Button>
          </Item>
        </Col>
        <Col xs={24} sm={12} md={12} lg={128} xl={126}>
          <Item
            label="中标文件"
            name="contactName"
            wrapperCol={{
              style: {
                textAlign: "right",
              },
            }}
          >
            <Button
              type="primary"
            >
              上传附件
            </Button>
          </Item>
        </Col>
        <Col xs={24} sm={12} md={128} lg={128} xl={126}>
          <Item
            label="其他附件"
            name="contactMobile"
            wrapperCol={{
              style: {
                textAlign: "right",
              },
            }}
          >
            <Button
              type="primary"
            >
              上传附件
            </Button>
          </Item>
        </Col>
        <Col span={24} >
        <Space size={50}>
             <Button
              type="primary"
            >
              下载模版
            </Button>
             <Button
              type="primary"
            >
              导入耗材
            </Button>
             <Button
              type="primary"
            >
              添加耗材
            </Button>
        </Space>
          
        </Col>
        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="负责人" name="productName"
           wrapperCol={{
              style: {
                textAlign: "left",
              },
            }}>
            <Select style={{ width: '100%' }} placeholder="请选择负责人">
              {/* 示例选项，可根据实际情况修改 */}
              <Option value="user1">用户1</Option>
              <Option value="user2">用户2</Option>
              <Option value="user3">用户3</Option>
            </Select>
          </Item>
        </Col>

        <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="甲乙供材" name="productName"
           wrapperCol={{
              style: {
                textAlign: "left",
              },
            }}>
            <Select style={{ width: '100%' }} placeholder="请选择供材方">
              {/* 示例选项，可根据实际情况修改 */}
              <Option value="user1">甲供材</Option>
              <Option value="user2">乙供材</Option>
              <Option value="user3">甲乙供材</Option>
            </Select>
          </Item>
        </Col>
         <Col xs={24} sm={12} md={12} lg={12} xl={12}>
          <Item label="供货商" name="productName"
           wrapperCol={{
              style: {
                textAlign: "left",
              },
            }}>
            <Select style={{ width: '100%' }} placeholder="请选择供货商">
              {/* 示例选项，可根据实际情况修改 */}
              <Option value="user1">A供货</Option>
              <Option value="user2">B供货</Option>
            </Select>
          </Item>
        </Col>
        <Col span={24}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20, alignItems: 'center', gap: 16 }}>
            <Typography.Title level={4} style={{ margin: 0 }}>监理方</Typography.Title>
            <Button type="primary" onClick={showSupervisorModal}>
              新增监理方信息
            </Button>
          </div>
          <Table columns={supervisorColumns} dataSource={supervisors} pagination={false} />
        </Col>
        <Modal
          title={supervisorEditingKey ? "编辑监理方信息" : "新增监理方信息"}
          visible={isSupervisorModalVisible}
          onOk={handleSupervisorModalOk}
          onCancel={handleSupervisorModalCancel}
        >
          <Form form={supervisorModalForm} layout="vertical">
            <Form.Item
              name="supervisorCompany"
              label="监理方"
              rules={[{ required: true, message: "请选择监理方" }]}
            >
              <Select style={{ width: '100%' }} placeholder="请选择监理方">
                {/* 示例选项，可根据实际情况修改 */}
                <Option value="user1">A监理方</Option>
                <Option value="user2">B监理方</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="supervisorName"
              label="监理负责人姓名"
              rules={[{ required: true, message: "请输入监理负责人姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="supervisorPhone"
              label="监理负责人电话"
              rules={[{ required: true, message: "请输入监理负责人电话" }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        <Col span={24}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20, alignItems: 'center', gap: 16 }}>
            <Typography.Title level={4} style={{ margin: 0 }}>施工方</Typography.Title>
            <Button type="primary" onClick={showModal}>
              新增施工方信息
            </Button>
          </div>
          <Table columns={columns} dataSource={constructionCompanies} pagination={false} />
        </Col>
        <Modal
          title={editingKey ? "编辑施工方信息" : "新增施工方信息"}
          visible={isModalVisible}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
        >
          <Form form={modalForm} layout="vertical">
            <Form.Item
              name="companyName"
              label="公司名称"
              rules={[{ required: true, message: "请选择公司名称" }]}
            >
              <Select style={{ width: '100%' }} placeholder="请选择公司名称">
                {/* 示例选项，可根据实际情况修改 */}
                <Option value="company1">A 施工公司</Option>
                <Option value="company2">B 施工公司</Option>
                <Option value="company3">C 施工公司</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="principalName"
              label="负责人姓名"
              rules={[{ required: true, message: "请输入负责人姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="phone"
              label="电话"
              rules={[{ required: true, message: "请输入电话" }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
          <Col span={24} >
        <Space size={50}>
             <Button
              type="primary"
            >
              提交
            </Button>
             <Button
              type="primary"
            >
              保存
            </Button>
             <Button
              type="primary"
            >
              返回
            </Button>
        </Space>
          
        </Col>
      </>
    );
  };

  return (
    <div className="pl-8 pr-8 pt-8 pb-8 flex flex-col justify-start items-center ">
      <Card
        title="新建项目详情"
        extra={
          <Button type="primary" onClick={() => navigate("/mt")}>
            返回
          </Button>
        }
        className="max-w-7xl mx-auto min-md:!min-w-[1280px]"
      >
        <Form form={form} layout="horizontal" className="uniform-label-width">
          <Row gutter={[24, 16]}>
            {/* <Col xs={24} sm={24} md={24} lg={24} xl={24}>
              <Item
                label="项目名称"
                name="contractCode"
                rules={[{ required: true, message: '请输入项目名称' }]}
              >
                <Input
                  className="!grow"
                  placeholder="请输入项目名称"
                  onBlur={handleContractCodeBlur}
                />
              </Item>
            </Col> */}
            {renderContractInfo()}
          </Row>
        </Form>
      </Card>
    </div>
  );
};

export default MaintainAdd;
